<?php
namespace App\Admin\Controllers\FileModel;
use App\Http\Controllers\Controller;
use Dcat\Admin\FormStep\Form as StepForm;
use App\Models\InputStepForm;
use App\Models\InformationList;
use Dcat\Admin\Form;
use Dcat\Admin\Admin;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request;
use PhpOffice\PhpWord\TemplateProcessor;
use PhpOffice\PhpWord\PhpWord;
use Dcat\Admin\Grid;
use Illuminate\Support\Facades\DB;
use Log;
// use Dcat\Admin\Widgets\Form;
class RetrofitInformationController extends Controller
{
    //电除尘改造信息调查表
    protected $options = [
        1 => '显示文本框',
        2 => '显示编辑器',
        3 => '显示文件上传',
        4 => '还是显示文本框',
    ];
    // use PreviewCode;
    public function index(Content $content)
    {
        return $content
            // ->body('<div style="margin:5px 0 15px;">'.$this->buildPreviewButton().'</div>')
            ->body($this->form())
            ->header('电除尘改造信息调查表')
            ->description('分步表单');
    }
    protected function form()
{
    Admin::js('/stepform/js/jquery.smartWizard.min.js');
    Admin::css('/stepform/css/step.css');
    return Form::make(new InputStepForm(), function (Form $form) {
            $form->title('电除尘改造信息调查表数据录入');
            $form->action('RetrofitInfostep');
            $form->disableListButton();
            $form->multipleSteps()
                ->remember() 
                ->width('100%')
                ->add('基本信息与本体参数', function (StepForm $step) use ($form) {
                    $step->text('projectname',trans('项目名称'))->required();
                    // $step->text('scmj',trans('除尘器收尘面积（m2）'))->required();
                    $step->text('clyql',"处理烟气量")->help(('单位:m3/h'))->required();
                    $step->text('mqpfqk',trans('目前排放情况'))->help('单位:mg/Nm3')->required();
                    $step->text('gzxg',trans('改造后期望达到的效果'))->required();
                    $step->text('tjsj',trans('最近一次本体检修时间及概况'))->required();
                    // $step->text('dcdmj',trans('电场断面积'))->help('单位：m2');
                    $step->text('ss',trans('室数'))->required();
                    $step->text('dcsl',trans('电场数量'))->required();
                    // $step->text('tjjj',trans('同极间距'))->required();
                    $step->table('dc3cs', trans('各电场参数'),function ($table){
                        $table->text('dc', '电场');
                        $table->text('同极间距','同极间距')->help('单位:mm');
                        $table->text('阴极排数','阴极排数')->help('单位:排');
                        $table->text('阳极排数','阳极排数')->help('单位:排');
                    });

                    $step->select('yinjzdxs',trans('阴极振打型式'))->options(['顶部振打'=>'顶部振打','侧传侧打'=>'侧传侧打','顶传侧打'=>'顶传侧打'])->required();
                    $step->select('yangjzdxs',trans('阳极振打型式'))->options(['顶部振打'=>'顶部振打','侧传侧打'=>'侧传侧打','顶传侧打'=>'顶传侧打','顶部侧部振打'=>'顶部+侧部振打'])->required();
                    $step->text('diyxcd',trans('电场有效长度'))->help('单位:mm')->required();
                    $step->text('dcyxgd',trans('电场有效高度'))->help('单位:mm')->required();
                    // $step->text('yinjps',trans('阴极排数'))->help('单位:排')->required();
                    // $step->text('yangjps',trans('阳极排数'))->help('单位:排')->required();
                    // $step->text('yxscmj',trans('有效收尘面积'))->required();
                    $step->text('ckfcnd',trans('保证出口粉尘浓度'))->required();
                    $step->text('xytlgy',trans('现有脱硫工艺'))->required();
                    $step->text('xytxgy',trans('现有脱硝工艺'))->required();
                    
                })
                ->add('电源信息与本体信息', function ($step) {
                    $step->multipleImage('gygtphoto', trans('高压柜柜体表头数据拍照'))->autoUpload()->url('step/files');
                    $step->multipleImage('kzgphoto', trans('控制柜在控制室的照片'))->autoUpload()->url('step/files');
                    $step->multipleImage('gygmpphoto', trans('现有高压柜铭牌照片'))->autoUpload()->url('step/files');
                    $step->multipleImage('yangjb', trans('阳极板情况'))->autoUpload()->url('step/files');
                    $step->text('yangjbremark',trans('阳极板问题数量与情况'));

                    $step->multipleImage('yangjzdg', trans('阳极振打杆'))->autoUpload()->url('step/files');
                    $step->text('yangjzdgremark',trans('阳极振打杆问题数量与情况'));

                    $step->multipleImage('yangjzdz', trans('阳极振打锤、振打砧'))->autoUpload()->url('step/files');
                    $step->text('yangjzdzremark',trans('阳极振打锤问题数量与情况'));

                    $step->multipleImage('yinjkj', trans('阴极框架情况'))->autoUpload()->url('step/files');
                    $step->text('yinjkjremark',trans('阴极框架问题数量与情况'));

                    $step->multipleImage('yinjx', trans('阴极线'))->autoUpload()->url('step/files');
                    $step->text('yinjxremark',trans('阴极线问题数量与情况'));

                    $step->multipleImage('ktfs', trans('壳体墙板腐蚀情况'))->autoUpload()->url('step/files');
                    $step->text('ktfsremark',trans('壳体墙板腐蚀问题数量与情况'));

                    $step->multipleImage('lbfbb', trans('喇叭分布板、槽形板情况'))->autoUpload()->url('step/files');
                    $step->text('lbfbbremark',trans('喇叭分布板、槽形板问题数量与情况'));

                });
        });
    }

    public function step(Request $request){
        $info = $request->all();
        if(empty($info['CURRENT_VALIDATION_STEP'])&&$info['ALL_STEPS']==1){//提交
            Log::info($info);
            //实例化 phpword 类
            $PHPWord = new PhpWord();
            //指定事先制作好的模板文件路径
            $templateProcessor = new TemplateProcessor(public_path("filemodel/retrofit_infomation.docx"));
            $templateProcessor->setValue('projectname', $info['projectname']);
            
            // $templateProcessor->setValue('kzgphoto', $info['kzgphoto']);
            $templateProcessor->setValue('clyql', $info['clyql']);
            $templateProcessor->setValue('mqpfqk', $info['mqpfqk']);
            $templateProcessor->setValue('gzxg', $info['gzxg']);
            $templateProcessor->setValue('tjsj', $info['tjsj']);
            
            $templateProcessor->setValue('ss',$info['ss']);
            $templateProcessor->setValue('dcsl',$info['dcsl']);
            // $templateProcessor->setValue('tjjj',$info['tjjj']);

            // $templateProcessor->setValue('yjjzdxs',$info['yjjzdxs']);
            $templateProcessor->setValue('diyxcd',$info['diyxcd']);
            $templateProcessor->setValue('dcyxgd',$info['dcyxgd']);
            $templateProcessor->setValue('yinjzdxs',$info['yinjzdxs']);
            $templateProcessor->setValue('yangjzdxs',$info['yangjzdxs']);
            
            $templateProcessor->setValue('ckfcnd',$info['ckfcnd']);
            $templateProcessor->setValue('xytlgy',$info['xytlgy']);
            $templateProcessor->setValue('xytxgy',$info['xytxgy']);

            //计算
            $info['dc3cs'] = array_values($info['dc3cs']);
            //除尘器收尘面积=（电场有效高度*电场有效长度*阴极排数（取一电场）*2*室数）$info['dc3cs'][0]['阴极排数']
            $yinjpss = $info['dc3cs'][0]['阴极排数']?:1;
            $ccscmj = $info['dcyxgd']*$info['diyxcd']*$yinjpss*2*$info['ss'];
            $templateProcessor->setValue('yxscmj',$ccscmj);
            $templateProcessor->setValue('scmj', $ccscmj);
            //电场断面积要 = （一电场阴极排数*电场有效高度*室数*一电场同极距）
            $tjjjs = $info['dc3cs'][0]['同极间距']?:1;
            $dcdmjs = $info['dc3cs'][0]['阴极排数']*$info['dcyxgd']*$info['ss']*$tjjjs;
            $templateProcessor->setValue('dcdmj',$dcdmjs);
            //流速=（处理烟气量/3600/电场断面积）
            $ls = $info['clyql']/3600/$dcdmjs;
            $templateProcessor->setValue('ls',$ls);
            //比集尘 =（有效收尘面积/处理烟气量*3600）
            $bjc = $ccscmj/$info['clyql']*3600;
            $templateProcessor->setValue('bjc',$bjc);
            if($info['dc3cs']){
                $dc3jjj = '';
                $dc3yinj = '';
                $dc3yangj = '';
                foreach($info['dc3cs'] as $key =>$val){
                    $dc3jjj = $dc3jjj.$val['dc'].'极间距'.$val['同极间距'].'; ';
                    $dc3yinj = $dc3yinj.$val['dc'].'阴极排数'.$val['阴极排数'].'; ';
                    $dc3yangj = $dc3yangj.$val['dc'].'阳极排数'.$val['阳极排数'].'; ';
                }
                $templateProcessor->setValue('tjjj',$dc3jjj);
                $templateProcessor->setValue('yinjps',$dc3yinj);
                $templateProcessor->setValue('yangjps',$dc3yangj);
            }

            // $str = storage_path('app/'.$info['gygtphoto']);
            // print_r($str);
            //高压柜柜体表头数据拍照
            if($info['gygtphoto']){
                $gygtphoto = explode(',',$info['gygtphoto']);
                $rows = count($gygtphoto);
                $templateProcessor->cloneRow('gygtphoto',$rows);//复制行
                for($a=0;$a<$rows;$a++){
                    $templateProcessor->setImageValue("gygtphoto#".($a+1),['path'=>storage_path('app/'.$gygtphoto[$a])]);
                }
            }
            
            //控制柜在控制室的照片
            if($info['kzgphoto']){
                $kzgphoto = explode(',',$info['kzgphoto']);
                $rowsb = count($kzgphoto);
                $templateProcessor->cloneRow('kzgphoto',$rowsb);//复制行
                for($b=0;$b<$rowsb;$b++){
                    $templateProcessor->setImageValue("kzgphoto#".($b+1),['path'=>storage_path('app/'.$kzgphoto[$b])]);
                }
            }
            // //高压柜铭牌照片
            // $templateProcessor->setImageValue('gygmpphoto',['path'=>storage_path('app/'.$info['gygmpphoto'])]);
            if($info['gygmpphoto']){
                $gygmpphoto = explode(',',$info['gygmpphoto']);
                $rowsc = count($gygmpphoto);
                $templateProcessor->cloneRow('gygmpphoto',$rowsc);//复制行
                for($c=0;$c<$rowsc;$c++){
                    $templateProcessor->setImageValue("gygmpphoto#".($c+1),['path'=>storage_path('app/'.$gygmpphoto[$c])]);
                }
            }
            // //阳极板情况
            if($info['yangjb']){
                $yangjb = explode(',',$info['yangjb']);
                $rowsd = count($yangjb);
                $templateProcessor->cloneRow('yangjb',$rowsd);//复制行
                for($d=0;$d<$rowsd;$d++){
                    $templateProcessor->setImageValue("yangjb#".($d+1),['path'=>storage_path('app/'.$yangjb[$d])]);
                }
            }
            $yangjbremark = !empty($yangjbremark)?:'';
            $templateProcessor->setValue('yangjbremark', $info['yangjbremark']);
            // //阳极振打杆
            if($info['yangjzdg']){
                $yangjzdg = explode(',',$info['yangjzdg']);
                $rowse = count($yangjzdg);
                $templateProcessor->cloneRow('yangjzdg',$rowse);//复制行
                for($e=0;$e<$rowse;$e++){
                    $templateProcessor->setImageValue("yangjzdg#".($e+1),['path'=>storage_path('app/'.$yangjzdg[$e])]);
                }
            }
            $yangjzdgremark = !empty($yangjzdgremark)?:'';
            $templateProcessor->setValue('yangjzdgremark', $info['yangjzdgremark']);
            // //阳极振打锤 振打砧 
            if($info['yangjzdz']){
                $yangjzdz = explode(',',$info['yangjzdz']);
                $rowsf = count($yangjzdz);
                $templateProcessor->cloneRow('yangjzdz',$rowsf);//复制行
                for($f=0;$f<$rowsf;$f++){
                    $templateProcessor->setImageValue("yangjzdz#".($f+1),['path'=>storage_path('app/'.$yangjzdz[$f])]);
                }
            }
            $yangjzdzremark = !empty($yangjzdzremark)?:'';
            $templateProcessor->setValue('yangjzdzremark', $info['yangjzdzremark']);
            // //阴极框架情况
            if($info['yinjkj']){
                $yinjkj = explode(',',$info['yinjkj']);
                $rowsg = count($yinjkj);
                $templateProcessor->cloneRow('yinjkj',$rowsg);//复制行
                for($g=0;$g<$rowsg;$g++){
                    $templateProcessor->setImageValue("yinjkj#".($g+1),['path'=>storage_path('app/'.$yinjkj[$g])]);
                }
            }
            $yinjkjremark = !empty($yinjkjremark)?:'';
            $templateProcessor->setValue('yinjkjremark', $info['yinjkjremark']);
            // //阴极线
            if($info['yinjx']){
                $yinjx = explode(',',$info['yinjx']);
                $rowsh = count($yinjx);
                $templateProcessor->cloneRow('yinjx',$rowsh);//复制行
                for($h=0;$h<$rowsh;$h++){
                    $templateProcessor->setImageValue("yinjx#".($h+1),['path'=>storage_path('app/'.$yinjx[$h])]);
                }
            }
            $yinjxremark = !empty($yinjxremark)?:'';
            $templateProcessor->setValue('yinjxremark', $info['yinjxremark']);
            // //壳体墙板腐蚀情况
            if($info['ktfs']){
                $ktfs = explode(',',$info['ktfs']);
                $rowsi = count($ktfs);
                $templateProcessor->cloneRow('ktfs',$rowsi);//复制行
                for($i=0;$i<$rowsi;$i++){
                    $templateProcessor->setImageValue("ktfs#".($i+1),['path'=>storage_path('app/'.$ktfs[$i])]);
                }
            }
            $ktfsremark = !empty($ktfsremark)?:'';
            $templateProcessor->setValue('ktfsremark', $info['ktfsremark']);
            // //喇叭分布板、槽形板情况
            if($info['lbfbb']){
                $lbfbb = explode(',',$info['lbfbb']);
                $rowsj = count($lbfbb);
                $templateProcessor->cloneRow('lbfbb',$rowsj);//复制行
                for($j=0;$j<$rowsj;$j++){
                    $templateProcessor->setImageValue("lbfbb#".($j+1),['path'=>storage_path('app/'.$lbfbb[$j])]);
                }
            }
            $lbfbbremark = !empty($lbfbbremark)?:'';
            $templateProcessor->setValue('lbfbbremark', $info['lbfbbremark']);
            unset($info['_file_']);
            unset($info['CURRENT_VALIDATION_STEP']);
            unset($info['ALL_STEPS']);
            unset($info['_token']);
            $data['admin_id'] = Admin::user()->id;
            $data['name'] = $info['projectname'].date('Y-m-d H:i');
            $data['data'] = $info;
            // $data['content'] = json_encode($info);
            // $insertData['content'] = json_encode($data);
            $insertData['name'] = $data['name'];
            $insertData['type'] = 1;
            $insertData['admin_id'] = Admin::user()->id;
            $insertData['created_at'] = date('Y-m-d H:i:s');
            $templateProcessor->saveAs(public_path('filemodellist/'.$data['name'].".docx"));
            InformationList::insert($insertData);
            return $this->form()->saving(function (Form $form) {
                // 清空缓存
                $form->multipleSteps()->flushStash();
                // 拦截保存操作
                return response(
                    $form->multipleSteps()
                        ->done()
                        ->render()
                );
            })->store();
        }
    }

    /**
     * 保存
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function store(Request $requset)
    {
        return $this->form()->saving(function (Form $form) {
            
            // 清空缓存
            $form->multipleSteps()->flushStash();
            // 拦截保存操作
            return response(
                $form->multipleSteps()
                    ->done()
                    ->render()
            );
        })->store();
    }

    public function list($id,Content $content){
        return $content
            ->header('表格列表')
            ->description()
            ->body($this->grid($id));
    }
    protected function grid($typeid)
    {
        return new Grid(InformationList::where(['admin_id'=>Admin::user()->id,'type'=>$typeid]), function (Grid $grid) {
            $grid->showActions();
            $grid->disableDeleteButton();
            $grid->disableQuickEditButton();
            $grid->disableViewButton();
            $grid->disableCreateButton();
            $grid->disableEditButton();
            $grid->fixColumns(2);
            
            $grid->column('id', 'ID');
            $grid->column('name', '名称');
            $grid->column('type','类型')->display(function($type) {
                return Db::table('xfy_info_model')->where(['id'=>$type])->value('name');;
            });
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $id = $actions->getKey();
                $edit_url = admin_base_path('downloadfile/'.$id);
                $actions->append("<a href='$edit_url'>下载</a>");
            });
        });
    }
}